<?php
require 'libs/QueryPath/QueryPath.php';

class Pbatis{
	public $configFilePath;
	public $connectionId;
	private $_conn;
	private static $mapper;

	public function __construct($mapperXML){
		if(!file_exists($mapperXML)){
			throw new Exception("FileNotExists:". $mapperXML);
		}
		self::$mapper = qp($mapperXML, 'mapper');
	}


	/**
	 * 设置Mapper配置文件路径
	 * @param String mapper配置文件路径
	 * @throws BatisException 当mapper配置文件不存在时
	 */
	public function setMapper($mapperXML){
		if(!file_exists($mapperXML)){
			throw new BatisException("FileNotExists:". $mapperXML);
			return false;
		}
		self::$mapper = qp($mapperXML, 'mapper');
		return $this;
	}

	function get_sql($sqlId, &$parameter=null) {
		return trim($this->replaceTag($sqlId, $parameter));
	}
    function replaceTag($sqlId, &$parameter=null) {
        $qp = qp(self::$mapper)->find('#' . $sqlId);
        $parameterClass = $qp->attr('parameterClass');
        $resultClass    = $qp->attr('resultClass');
        $cacheId		= $qp->attr('cacheId');
        $isCache		= $qp->attr('cache');
        $cacheTime		= $qp->attr('cacheTime');
        $prepare		= $qp->attr('prepare');

        $sqlText		= '';
        $childs = $qp->contents();
        foreach ($childs as $child) {
            if (@$child->tag() == 'if') {
                $_code = $child->attr('test');
                $_text = $this->_dynamicCheck($_code, $parameter) ? $child->text() : '';
            } else {
                $_text = $child->text();
            }
            $sqlText .= $_text;
        }

        preg_match_all( "/#(.*)#/", $sqlText, $match );

        $sqlText 		= self::replaceSqlTag($sqlText, $match);

        return $sqlText;
    }

    private function _doParseTag($sqlText) {
        preg_match_all( "/#(.*)#/", $sqlText, $match );

        return self::replaceSqlTag($sqlText, $match);
    }
    private function _dynamicCheck($code, $data) {
        extract($data);
        return eval('return '.$code.';');
    }

	/**
	 * 替换文本中所有#id#为Mapper配置文件中指定sql标签的文本
	 * @param String $sqlText
	 * @param Array $match
	 * @throws BatisException 当指定id的sql标签不存在时
	 */
	public static function replaceSqlTag($sqlText, $match){
		if(!empty($match)){
			foreach($match[1] as $id){
				$key = '#'. $id .'#';
				if(!empty($replaces))
				if(key_exists($key, $replaces)) continue;

				if( ($search = qp(self::$mapper)->find('sql[id=' . $id .']')->text()) == null){
					throw new Exception('Sql Tag Error : ' . $id . 'Does not exist');
					return false;
				}else{
					$replaces[$key] = $search;
				}
			}

			if(!empty($replaces))
			foreach($replaces as $k=>$v){
				$sqlText = str_replace($k, $v, $sqlText);
			}
			return $sqlText;
		}
	}
}